//This example code is in the Public Domain (or CC0 licensed, at your option.)
//By Evandro Copercini - 2018
//
//This example creates a bridge between Serial and Classical Bluetooth (SPP)
//and also demonstrate that SerialBT have the same functionalities of a normal Serial

#include <Adafruit_NeoPixel.h>
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif


#define PIN_POWER       2
int batteryPower=0;                       //电池电量ADC值
int samTime;                              //电池电量采样时间记录器
#define FRE_BATTERY_POWER        2        //电池电量采样时间频率 单位s
int samPowerTimes;                        //电池采样次数


BluetoothSerial SerialBT;


#define   Vbat_min  3.65  //低电量时候的电压值
#define   Nadc_min  1590  //低电量时候的ADC读数
#define   Vbat_max  4.25  //满电量时候的电压值
#define   Nadc_max  1910  //满电量时候的ADC读数
float coeff_a=(Nadc_max-Nadc_min)/(Vbat_max-Vbat_min);
float coeff_b=Nadc_max-coeff_a*Vbat_max;


void setup() {
  SerialBT.begin("TestBattry"); //Bluetooth device name
  Serial.begin(115200); //Bluetooth device name

  //复位电池采样次数
  samPowerTimes=0;

}

void loop() {
 
    sendBatteryPower();
}

void sendBatteryPower(){
  
  if(samTime!=millis()/1000)//一秒读取电压一次，并且取最大值作为电池电量
  {
    samTime=millis()/1000;
    if(samPowerTimes<FRE_BATTERY_POWER){  samPowerTimes++;  if(batteryPower < analogRead(PIN_POWER)){batteryPower = analogRead(PIN_POWER);}}
    else {
      //到达时间后，发送电量数据，并且复位计数器和电量计数
      samPowerTimes=0;
      //ADC读数
      SerialBT.print("ADC:"+String(batteryPower)+"--");
      //实际电压
      SerialBT.print("电压："+String((batteryPower-coeff_b)/coeff_a)+"--");
      //100%电量
      SerialBT.print("电量："+String((batteryPower-Nadc_min)*100/(Nadc_max-Nadc_min)));
      batteryPower=0;
      }
    } 
  }
